<template>
  <div class="app-container">
    <el-row style="height: 51px">
      <el-col :span="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch1"
          style="display: inline-block"
        >
          <el-form-item label="起始时间" prop="startTime">
            <el-date-picker
              v-model="queryParams.startTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              placeholder="选择日期时间"
              :value-format="'yyyy-MM-dd HH:mm'"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="截止时间" prop="endTime">
            <el-date-picker
              v-model="queryParams.endTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              placeholder="选择日期时间"
              :value-format="'yyyy-MM-dd HH:mm'"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="8">
      <el-col :span="12">
        <div style="height: 500px" ref="lineEcharts1"></div>
      </el-col>
      <el-col :span="2" class="check-radio">
        <el-radio-group v-model="radioValue" @input="switchType">
          <el-radio label="点数">点数</el-radio>
          <el-radio label="虚警概率">虚警概率</el-radio>
          <el-radio label="识别概率">识别概率</el-radio>
          <el-radio label="航迹批次">航迹批次</el-radio>
        </el-radio-group>
      </el-col>
      <el-col :span="10">
        <div style="height: 500px" ref="lineEcharts2"></div>
      </el-col>
    </el-row>

    <div class="testTable">
      <el-row>
        <span class="hide">
          <el-form
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            style="display: inline-block; margin-left: 20px"
          >
            <el-col :span="1.5">
              <el-checkbox-group v-model="ids" @change="handleClickIds">
                <el-checkbox
                  v-for="item in practicalSource"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" size="mini" @click="handleTestQuery"
                >确定</el-button
              >
            </el-col>
          </el-form>
        </span>
      </el-row>
    </div>
    <el-row :gutter="8">
      <el-col :span="12">
        <el-tabs
          type="border-card"
          v-model="activeName"
          @tab-click="handleTabsClick"
        >
          <el-tab-pane label="外源关联" name="allSource">
            <el-table v-loading="loading" :data="dataList">
              <el-table-column
                prop="setCode"
                label="通道"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="setCode"
                label="帧数"
                align="center"
                v-if="activeName == 'seleSource'"
              ></el-table-column>
              <el-table-column
                prop="setName"
                label="批数"
                align="center"
              ></el-table-column>
              <el-table-column
                label="识别概率[G点/总点]"
                align="center"
                prop="setDesc"
              ></el-table-column>
              <el-table-column
                label="识别概率[(G点+M点)/总点]"
                align="center"
                prop="sourceCode"
              ></el-table-column>
              <el-table-column
                prop="setType"
                label="虚警概率"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="setType"
                label="删批频次"
                align="center"
              ></el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="实装匹配" name="actualSource"></el-tab-pane>
          <el-tab-pane label="自身" name="seleSource"> </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="12">
        <el-row>
          <el-col :span="1.5" style="margin-bottom:10px">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="sampleExportHandle"
              >样本导出</el-button
            >
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="dataListR">
          <el-table-column
            prop="setCode"
            label="样本类型"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="setCode"
            label="航迹批号"
            align="center"
            v-if="activeName == 'seleSource'"
          ></el-table-column>
          <el-table-column
            prop="setName"
            label="帧序号"
            align="center"
          ></el-table-column>
          <el-table-column
            label="波位号"
            align="center"
            prop="setDesc"
          ></el-table-column>
          <el-table-column
            label="距离单元"
            align="center"
            prop="sourceCode"
          ></el-table-column>
          <el-table-column
            prop="setType"
            label="方位单元"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="setType"
            label="多普勒单元"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="setType"
            label="航迹点时间"
            align="center"
          ></el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getDict,
  getBatchModDeviationStatListModal,
  getDataQueryDateForTable,
  getDataQueryDate,
  exportDownLoadSample
} from "@/api/service";
import Edit from "./components/edit.vue";
import * as echarts from "echarts";
import moment from "moment";

export default {
  name: "Datasource",
  components: { Edit },
  data() {
    return {
      // 遮罩层
      loading: true,
      radioValue: "点数",
      // 显示搜索条件
      showSearch: false,
      showSearch1: true,
      // 检测/虚警概率统计曲线数据
      dataList: [],
      dataListR: [], //右边表格
      historyData: [],
      //检测/虚警概率统计表格数据
      dataVersionList: [],
      // 重新渲染表格状态
      refreshTable: true,
      customFlag: false,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        startTime: moment().subtract(1, "days").format("YYYY-MM-DD HH:mm"),
        endTime: moment(new Date()).format("YYYY-MM-DD HH:mm"),
      },
      ids: [],
      sourceCodeDatas: [],
      //弹窗参数
      dialogVisible: false,
      dialogTitle: "",
      dialogOpen: false,
      dialogData: {},
      activeName: "allSource",
      mulData: [],
      socket: null,
      XAsisForEchart: [],
      nowDataForEcharts: [],
      nowDataForEchart: [],
      nowDataForTable: [],
      wsServer: "ws://172.168.1.47:8899/websocket/3",
      limitConnect: 10, //断线重联次数
      timeConnect: 0,
      nowDataForEchartsFilter: [],
      practicalSource: [],
      parctiaclTableData: [],
    };
  },
  created() {
    getDict("point_source").then((res) => {
      if (res.code === 200) {
        let data = res.data.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue,
          };
        });
        this.mulData = data;
      }
    });
    getDict("practical_source").then((res) => {
      if (res.code === 200) {
        let data = res.data.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue,
          };
        });
        this.practicalSource = data;
      }
    });
  },
  mounted() {
    if (!this.customFlag) {
      this.getDateQueryData();
    }
  },
  methods: {
    //根据选择处理的枚举类型
    switchType(val) {
      console.log(254, val);
      this.radioValue = val;
    },
    handleChangeSwitch() {
      if (this.customFlag) {
        this.showSearch1 = false;
        this.websocketInit(this.wsServer);
      } else {
        this.showSearch1 = true;
      }
    },
    getPointNum(iten, xDate, sourceId) {
      if (iten.find((itey) => itey?.sendTime == xDate)) {
        return {
          sendTime: xDate,
          sourceId: sourceId,
          pointNum: iten.find((itey) => itey?.sendTime == xDate)?.pointNum,
        };
      } else {
        return {
          sendTime: xDate,
          sourceId: sourceId,
          pointNum: 0,
        };
      }
    },
    websocketInit(service) {
      let socket = { current: null };
      let dataFilterEcharts = [];
      let deviationFilterData = [];
      let allDataDevia = [];
      //全部的
      let tableDataNow = [];
      if (!socket.current) {
        socket.current = new WebSocket(service);
        socket.current.onopen = function () {
          console.log("已建立TCP服务器");
        };
        console.log(socket.current);
        socket.current.onmessage = (e) => {
          if (JSON.parse(e.data)?.resType === 1005) {
            let item = JSON.parse(e.data).data;
            tableDataNow.push(item);
            let dataAll = JSON.parse(JSON.stringify(tableDataNow));
            //处理左侧的echart的图表
            // x轴
            let dataSendTime = dataAll.map((item) => {
              return item.sendTime;
            });
            let xDataEcharts = [...new Set(dataSendTime)];
            if (xDataEcharts.length > 20) {
              this.XAsisForEchart = xDataEcharts.slice(-20);
            } else {
              this.XAsisForEchart = xDataEcharts;
            }

            //按照sourceId分割成多个数组
            let data = dataAll.reduce(
              (r, x) => ((r[x.sourceId] || (r[x.sourceId] = [])).push(x), r),
              {}
            );
            dataFilterEcharts = Object.keys(data).map((x) => data[x]);
            for (let j = 0; j < dataFilterEcharts.length; j++) {
              let pointArr = [];
              for (
                let i = 0;
                i < xDataEcharts.sort((a, b) => a - b).length;
                i++
              ) {
                pointArr.push(
                  this.getPointNum(
                    dataFilterEcharts[j],
                    xDataEcharts[i],
                    dataFilterEcharts[j][0]["sourceId"]
                  )
                );
              }

              dataFilterEcharts[j] = pointArr;
            }

            let newDataSlice = [];
            if (
              dataFilterEcharts[0]?.length > 20 ||
              dataFilterEcharts[1]?.length > 20 ||
              dataFilterEcharts[2]?.length > 20
            ) {
              newDataSlice = [
                dataFilterEcharts[0]?.slice(-20),
                dataFilterEcharts[1]?.slice(-20),
                dataFilterEcharts[2]?.slice(-20),
              ];
              this.nowDataForEcharts = newDataSlice;
            } else {
              this.nowDataForEcharts = dataFilterEcharts;
            }

            //处理实时的表格
            let arr = dataAll.reverse();
            const uniqueArr1 = Array.from(
              new Set(arr.map((item) => item.sourceId))
            ).map((sourceId) => {
              return arr.find((item) => item.sourceId === sourceId);
            });

            let dataFilter = uniqueArr1.reverse();
            // 处理右侧的图表
            let data1 = dataFilter.map((item) => {
              return item?.sourceId;
            });
            let data2 = dataFilter.map((item) => {
              return item?.pointNum;
            });
            this.nowDataForEchart = [data1, data2];
            this.nowDataForTable = dataFilter;
          } else if (JSON.parse(e.data)?.resType === 1006) {
            let item = JSON.parse(e.data).data;
            allDataDevia.push(item);
            let dataAll = JSON.parse(JSON.stringify(allDataDevia));

            let dataSendTime = dataAll.map((item) => {
              return item.sendTime;
            });
            let xDataEcharts = [...new Set(dataSendTime)];

            let data = dataAll.reduce(
              (r, x) => ((r[x.sourceId] || (r[x.sourceId] = [])).push(x), r),
              {}
            );
            deviationFilterData = Object.keys(data).map((x) => data[x]);
            for (let j = 0; j < deviationFilterData.length; j++) {
              let pointArr = [];
              for (
                let i = 0;
                i < xDataEcharts.sort((a, b) => a - b).length;
                i++
              ) {
                pointArr.push(
                  this.getPointNum(
                    deviationFilterData[j],
                    xDataEcharts[i],
                    deviationFilterData[j][0]["sourceId"]
                  )
                );
              }

              deviationFilterData[j] = pointArr;
            }
            let newDataSlice = [];
            if (
              deviationFilterData[0]?.length > 20 ||
              deviationFilterData[1]?.length > 20
            ) {
              newDataSlice = [
                deviationFilterData[0]?.slice(-20),
                deviationFilterData[1]?.slice(-20),
              ];
              this.nowDataForEchartsFilter(newDataSlice);
            } else {
              this.nowDataForEchartsFilter(deviationFilterData);
            }
            //虚警概率
          } else if (JSON.parse(e.data)?.resType === 1007) {
            let item = JSON.parse(e.data).data;
            let data = sessionStorage.getItem("fakerAlarmNow")
              ? JSON.parse(sessionStorage.getItem("fakerAlarmNow"))
              : [];
            data.push(...item);
            sessionStorage.setItem("fakerAlarmNow", JSON.stringify(data));
            //检测概率
          } else if (JSON.parse(e.data)?.resType === 1008) {
            let item = JSON.parse(e.data).data;
            let data = sessionStorage.getItem("detectionAlarmNow")
              ? JSON.parse(sessionStorage.getItem("detectionAlarmNow"))
              : [];
            data.push(...item);
            sessionStorage.setItem("detectionAlarmNow", JSON.stringify(data));
          }
        };

        socket.current.onclose = function () {
          reconnet(service);
        };
      }
    },
    initEcharts() {
      //曲线图 left
      const lineEcharts1 = echarts.init(this.$refs.lineEcharts1);
      let option = {};
      if (this.customFlag) {
        //实时
        console.log("now");
        option = {
          title: {
            text: `实时累计点数处理`,
            left: "center",
          },
          tooltip: {
            trigger: "axis",
          },
          legend: {
            show: true,
            left: "5%",
            top: "5%",
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: "none",
              },
              dataView: { readOnly: false },
              magicType: { type: ["line", "bar"] },
              restore: {},
              saveAsImage: {},
            },
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: xAsisForEchart,
          },
          yAxis: [
            {
              type: "value",
              axisLabel: {
                formatter: "{value}",
              },
            },
            {
              type: "value",
              name: "偏差分析",
              axisLabel: {
                formatter: "{value}",
              },
            },
          ],
          series: [
            {
              name: this.getLabelNow(
                this.nowDataForEcharts?.[1]?.map((item) => item?.sourceId)?.[0]
              ),
              type: "line",
              data: this.nowDataForEcharts?.[1]?.map((item) => item?.pointNum),
              yAxisIndex: 0,
            },
          ],
        };
      } else {
        console.log("history");
        //历史
        option = {
          title: {
            text: `历史累计${this.radioValue}处理`,
            left: "center",
            top: "20px",
          },
          tooltip: {
            trigger: "axis",
          },
          legend: {
            show: true,
            left: "5%",
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: "none",
              },
              dataView: { readOnly: false },
              magicType: { type: ["line", "bar"] },
              restore: {},
              saveAsImage: {},
            },
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: this.historyData?.xdates?.map((item) =>
              moment(item)?.format("YYYY-MM-DD HH:mm:ss")
            ),
          },
          yAxis: [
            {
              type: "value",
              axisLabel: {
                formatter: "{value}",
              },
            },
            {
              type: "value",
              name: "偏差分析",
              axisLabel: {
                formatter: "{value}",
              },
            },
          ],
          series: this.getSeriesData(),
        };
      }
      lineEcharts1.setOption(option);

      //right
      const lineEcharts2 = echarts.init(this.$refs.lineEcharts2);
      console.log("right");
      let option1 = {};
      option1 = {
        animation: true,
        animationThreshold: 2000,
        animationDuration: 1000,
        animationEasing: "cubicOut",
        animationDelay: 0,
        animationDurationUpdate: 300,
        animationEasingUpdate: "cubicOut",
        animationDelayUpdate: 0,
        xAxis: {
          type: "value",
        },
        grid: {
          left: "17%",
        },
        tooltip: {
          trigger: "axis",
        },
        yAxis: {
          type: "category",
          data: this.nowDataForEchart[0]?.map((iten) => {
            if (iten == this.mulData[0]?.value) {
              return this.mulData[0]?.label;
            } else if (iten == this.mulData[1]?.value) {
              return this.mulData[1]?.label;
            } else {
              return this.mulData[2]?.label;
            }
          }),
        },
        series: [
          {
            type: "bar",
            data: this.nowDataForEchart[1]?.map((iten, index) => {
              return {
                value: iten,
                itemStyle: {
                  color: ["#9fe080", "#5c7bd9", "#ff7070"][index],
                },
              };
            }),
          },
        ],
      };
      lineEcharts2.setOption(option1);
    },
    handleClickIds(val) {
      console.log(546, val);
      this.ids = val;
      console.log(this.ids);
    },
    //查询历史数据
    getDateQueryData() {
      this.loading = true;
      getDataQueryDate(this.queryParams).then((res) => {
        console.log("查询历史数据", res);
        if (res.code === 200) {
          res?.data?.xdates?.push(this.queryParams.endTime);
          res?.data?.xdates?.unshift(this.queryParams.startTime);
          this.mulData
            .map((item) => item.value)
            .map((iten) => {
              res?.data?.ypointNums?.[iten]?.push(0);
              res?.data?.ypointNums?.[iten]?.unshift(0);
            });
          for (let key in res?.data?.pointNumDiffs) {
            res?.data?.pointNumDiffs[key]?.push(0);
            res?.data?.pointNumDiffs[key]?.unshift(0);
          }
          this.historyData = res.data;
          this.loading = false;
          this.initEcharts();
        }
      });
    },
    //历史折线图的series
    getSeriesData() {
      let series;
      series = Object.values(this.historyData?.ypointNums || {})?.map(
        (item, indey) => {
          return {
            name: Object.keys(this.historyData?.ypointNums || {})?.map(
              (iten, index) => {
                if (iten == this.mulData[0]?.value) {
                  return this.mulData[0]?.label;
                } else if (iten == mulData[1]?.value) {
                  return this.mulData[1]?.label;
                } else {
                  return this.mulData[2]?.label;
                }
              }
            )[indey],
            type: "line",
            data: item,
            yAxisIndex: 0,
          };
        }
      );
      for (let key in this.historyData?.pointNumDiffs) {
        series.push({
          name: `偏差分析${key}`,
          type: "line",
          data: this.historyData?.pointNumDiffs[key],
          yAxisIndex: 1,
          markLine: {
            itemStyle: {
              normal: {
                label: {
                  formatter: "偏差调整",
                },
              },
            },
            lineStyle: {
              color: "yellowGreen",
            },
            symbol: "none",
          },
        });
      }
      return series;
    },
    getTestLines() {
      this.loading = true;
      getBatchModDeviationStatListModal("spotevalution8203").then(
        (response) => {
          console.log(537, response);
          this.dataVersionList = response.data.list;
          this.loading = false;
        }
      );
    },

    //检测/虚警概率统计表格数据
    getTestTables() {
      this.loading = true;
      let data = {
        startTime: moment(this.queryParams.startTime).format(
          "YYYY-MM-DD HH:mm"
        ),
        endTime: moment(this.queryParams.endTime).format("YYYY-MM-DD HH:mm"),
        matchSourceIds: this.ids,
      };
      console.log(564, data);
      getDataQueryDateForTable(data).then((res) => {
        console.log(565, res);
        if (res.code === 200) {
          this.parctiaclTableData = res?.data?.sourceCounts;
          this.loading = false;
        } else {
          message.warning(res.msg);
        }
        console.log(this.parctiaclTableData);
      });
    },
    getLabelNow(params) {
      let data = this.mulData.map((item) => {
        if (params == item?.value) {
          return item?.label;
        }
      });
      return data.filter((item) => item)[0];
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 历史
      this.getTestTables();
    },
    //检测/虚警概率统计表格查询
    handleTestQuery() {
      this.getTestTables();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //样本导出
    sampleExportHandle() {
      let data = {
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
      };
      exportDownLoadSample(data).then((res) => {});
    },
    // tabs click
    handleTabsClick(tab) {
      console.log("tabsclick", tab.name);
      switch (tab.name) {
        case "allSource":
          this.showSearch = false;
          // this.getTestTables();
          this.dataList = this.historyData;
          break;
        case "actualSource":
          this.showSearch = true;
          this.getTestTables();
          break;
        default:
          this.showSearch = false;
          this.dataList = this.historyData;
      }
    },
  },
};
</script>
<style scoped>
.testTable {
  height: 40px;
  line-height: 40px;
}
.check-radio {
  height: 500px;
  line-height: 500px;
}
.check-radio .el-radio-group .el-radio {
  height: 26px;
  line-height: 26px;
}
</style>
